#include <jni.h>
#include <string>
#include "AndroidLog.h"
#include "Queue.h"
#include "RtmpPush.h"
#include "CallJava.h"
extern "C"
{
#include "librtmp/rtmp.h"
}

RtmpPush * rtmpPush = NULL;
CallJava *mCallJava = NULL;
JavaVM *javaVM = NULL;

extern "C"
JNIEXPORT void JNICALL
Java_com_wq_livepusher_push_PushVideo_initPush(JNIEnv *env, jobject thiz, jstring push_url) {
    // TODO: implement initPush()
    LOGD("initPush");
    const char *pushUrl = env->GetStringUTFChars(push_url, 0);
    mCallJava = new CallJava(javaVM, env, &thiz);
    rtmpPush = new RtmpPush(pushUrl, mCallJava);
    rtmpPush->init();

    env->ReleaseStringUTFChars(push_url, pushUrl);
}
extern "C"
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
{
    javaVM = vm;
    JNIEnv* env;
    if (vm->GetEnv((void**)&env, JNI_VERSION_1_4) != JNI_OK)
    {
        if(LOG_SHOW)
        {
            LOGE("GetEnv failed!");
        }
        return -1;
    }
    return JNI_VERSION_1_4;
}
extern "C"
JNIEXPORT void JNICALL JNI_OnUnload(JavaVM* vm, void* reserved){
    javaVM = NULL;
}
extern "C"
JNIEXPORT void JNICALL
Java_com_wq_livepusher_push_PushVideo_pushSPSPPS(JNIEnv *env, jobject thiz, jbyteArray sps_,
                                                 jint sps_len, jbyteArray pps_, jint pps_len) {
    // TODO: implement pushSPSPPS()
    jbyte *sps = env->GetByteArrayElements(sps_, NULL);
    jbyte *pps = env->GetByteArrayElements(pps_, NULL);

    // TODO
    if(rtmpPush != NULL)
    {
        rtmpPush->pushSPSPPS(reinterpret_cast<char *>(sps), sps_len, reinterpret_cast<char *>(pps), pps_len);
    }

    env->ReleaseByteArrayElements(sps_, sps, 0);
    env->ReleaseByteArrayElements(pps_, pps, 0);
}extern "C"
JNIEXPORT void JNICALL
Java_com_wq_livepusher_push_PushVideo_pushVideoData(JNIEnv *env, jobject thiz, jbyteArray data_,
                                                    jint data_len, jboolean keyframe) {
    // TODO: implement pushVideoData()
    jbyte *data = env->GetByteArrayElements(data_, NULL);
    // TODO
    if(rtmpPush != NULL)
    {
        rtmpPush->pushVideoData(reinterpret_cast<char *>(data), data_len, keyframe);
    }
    env->ReleaseByteArrayElements(data_, data, 0);
}